package com.ruoyi.user.service;

import com.aliyun.alimt20181012.Client;
import com.aliyun.alimt20181012.models.TranslateRequest;
import com.aliyun.alimt20181012.models.TranslateResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.user.model.TranslateProperties;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: houyong
 * @date: 2025年11月18日 17:29
 */
@Service
public class TranslateService {
    // Cache expiration time (e.g., 1 hour)
    private static final long CACHE_EXPIRE_TIME = 30L;
    private final Client client;
    private final RedisService redisService;

    public TranslateService(TranslateProperties properties, RedisService redisService) throws Exception {
        Config config = new Config()
                .setAccessKeyId(properties.getAccessKeyId())
                .setAccessKeySecret(properties.getAccessKeySecret())
                .setEndpoint(properties.getEndpoint());
        this.client = new Client(config);
        this.redisService = redisService;
    }

    /**
     * Translate text
     *
     * @param formatType     格式类型（html, text）
     * @param scene          场景（默认：general, 商品标题（title），商品描述（description），商品沟通（communication），医疗（medical），社交（social)，金融（finance））
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @param text           待翻译文本
     * @return
     */
    public String translate(String formatType, String scene, String sourceLanguage, String targetLanguage, String text) {
        if (StringUtils.isBlank(text)) {
            formatType = "text";
        }
        if (StringUtils.isBlank(scene)) {
            scene = "general";
        }
        if (StringUtils.isBlank(sourceLanguage)) {
            sourceLanguage = "zh";
        }
        if (StringUtils.isBlank(targetLanguage)) {
            targetLanguage = "en";
        }

        // Generate cache key
        String cacheKey = generateCacheKey(formatType, scene, sourceLanguage, targetLanguage, text);
        // Try to get from cache first
        String cachedResult = redisService.getCacheObject(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        try {
            TranslateRequest request = new TranslateRequest();
            request.setFormatType(formatType);

            request.setSourceLanguage(sourceLanguage);
            request.setTargetLanguage(targetLanguage);
            request.setSourceText(text);

            request.setScene(scene);
            TranslateResponse translate = client.translate(request);
            String result = translate.getBody().getData().getTranslated();
            // Cache the result
            if (result != null) {
                redisService.setCacheObject(cacheKey, result, CACHE_EXPIRE_TIME, TimeUnit.DAYS);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Generate unique cache key based on translation parameters
     */
    private String generateCacheKey(String formatType, String scene, String sourceLanguage, String targetLanguage, String text) {
        return "translate:" + formatType + ":" + scene + ":" + sourceLanguage + ":" + targetLanguage + ":" + text.hashCode();
    }
}

